#!/usr/bin/env bash
TEST_PATH="`dirname "$0"`"
SOURCE_PATH="${TEST_PATH}/src"
BUILD_PATH="${TEST_PATH}/build"
INSTALLED=false

POSITIONAL=()
while [ $# -gt 0 ]
do
  case $1 in
    --installed)
      INSTALLED=true
      shift
      ;;
    *)
      POSITIONAL+=$1
      shift
      ;;
  esac
done
set -- "${POSITIONAL[@]}"
mkdir -p "${BUILD_PATH}"

if ${INSTALLED}
then
  gcc -o "${BUILD_PATH}/nested_function" "${SOURCE_PATH}/main.c" ${LDFLAGS} -lcexceptions
  BUILT=$?
else
  DISTR_LIB_PATH=$(realpath --relative-to="$(pwd)" "${TEST_PATH}/../../build/lib/")
  DISTR_INC_PATH=$(realpath --relative-to="$(pwd)" "${TEST_PATH}/../../build/include/")
  #C_INCLUDE_PATH="${C_INCLUDE_PATH}:${DISTR_INC_PATH}"\
  gcc -o "${BUILD_PATH}/nested_function"\
    "${SOURCE_PATH}/main.c"\
    -I${DISTR_INC_PATH} -L${DISTR_LIB_PATH} -lcexceptions
  BUILT=$?
  LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${DISTR_LIB_PATH}"
fi
if [ ${BUILT} -eq 0 ]
then
  LD_LIBRARY_PATH="${LD_LIBRARY_PATH}" "${BUILD_PATH}/nested_function"
fi